package com.dk.jwzx;

import com.dk.jwzx.bean.Student;
import com.dk.jwzx.bean.Subject;

import java.util.*;
import java.util.stream.Stream;

public final class JwzxHelper {

    private static Jwzx jwzx;

    static {
        jwzx=new JwzxImpl();
        jwzx.init();
    }

    private JwzxHelper(){}

    public static int getWeek(){
        return jwzx.getWeek();
    }

    /**
     * 获取当周的课表
     * @param stuId
     * @return
     */
    public static Map<Integer, List<Subject>> getStudentSubjects(String stuId){
        Map<Integer, List<Subject>> studentSubjects = jwzx.getStudentSubjects(stuId);
        int week=getWeek();
        List<Subject> subjects = studentSubjects.get(week);
        return doSubjectList(subjects);
    }

    /**
     * 返回Map<星期几,星期几对应的课程>
     * @param stuId
     * @param week 第几周
     * @return
     */
    public static Map<Integer, List<Subject>> getSubjectsByWeek(String stuId,int week){
        Map<Integer, List<Subject>> map=jwzx.getStudentSubjects(stuId);
        List<Subject> list=map.get(week);
        return doSubjectList(list);
    }

    public static Student getStudentInfo(String stuId){
        return jwzx.getStudentInfo(stuId);
    }

    //将这周无序的课表转化成星期一到星期五的有序课表
    private static Map<Integer,List<Subject>> doSubjectList(List<Subject> list){
        Map<Integer,List<Subject>> subjects=new HashMap<>();
        for(int i=1;i<=5;i++){
            subjects.put(i,new ArrayList<>());
        }

        if(list!=null){
            for(Subject s:list){
                int day=s.getDay();
                if(subjects.containsKey(day)){
                    subjects.get(day).add(s);
                }
            }

            for(int i=1;i<=5;i++){
                List<Subject> l=subjects.get(i);
                List<Subject> finish=finishSubjectList(l);
                subjects.put(i,finish);
            }
        }

        return subjects;
    }

    //将之前的List添加Blank-Subject
    private static List<Subject> finishSubjectList(List<Subject> l){
        l.sort((a,b)->a.getTime()[0]-b.getTime()[0]);
        List<Subject> finish=new ArrayList<>();

        if(l.size()>=1){

            //判断是否是从第一节课开始
            if(l.get(0).getTime()[0]>1){
                int end=l.get(0).getTime()[0]-1;
                Subject blank=new Subject();
                blank.setBlank(true);
                blank.setTime(new int[]{1,end});
                finish.add(blank);
            }

            for(int j=0;j<l.size()-1;j++){
                int begin=l.get(j).getTime()[1]+1;
                int end=l.get(j+1).getTime()[0]-1;
                if(begin<end){
                    Subject blank=new Subject();
                    blank.setBlank(true);
                    blank.setTime(new int[]{begin,end});
                    finish.add(l.get(j));
                    finish.add(blank);
                }else finish.add(l.get(j));
            }
            finish.add(l.get(l.size()-1));
        }

        return finish;
    }
}
